import 'package:flutter/material.dart';

class HomeSortMenuView extends StatefulWidget {
  final List<String> titleArr;
  final int selectIndex;
  final Function(int)? callback;
  final String gapChar;

  const HomeSortMenuView(this.titleArr, {Key? key, this.selectIndex = 0, this.callback, this.gapChar = '/'})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _HomeSortMenuViewState();
  }
}

class _HomeSortMenuViewState extends State<HomeSortMenuView> {
  int selectIndex = 0;

  @override
  void initState() {
    selectIndex = widget.selectIndex;
    super.initState();
  }

  @override
  void didUpdateWidget(covariant HomeSortMenuView oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> widgetArr = [];
    for (int i = 0; i < widget.titleArr.length; i++) {
      widgetArr.add(_buildMenuButton(widget.titleArr[i], i == selectIndex, i));
    }
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: widgetArr,
    );
  }

  Widget _buildMenuButton(String text, bool isSelected, int index) {
    bool isLast = index == (widget.titleArr.length - 1);
    return InkWell(
      onTap: () {
        selectIndex = index;
        setState(() {});
        widget.callback?.call(index);
      },
      child: Container(
        padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              text,
              style: TextStyle(
                fontSize: 14,
                color: isSelected ? Color(0xE5FFFFFF) : const Color(0x73FFFFFF),
              ),
            ),
            const SizedBox(width: 12),
            if (isLast)
              const SizedBox(width: 12)
            else
              Text(
                widget.gapChar,
                style: TextStyle(
                  fontSize: 14,
                  color: Color(0x73FFFFFF),
                ),
              ),
            const SizedBox(width: 12),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
